import os
import sys
import logging

from google.appengine.ext import db

import base.Error as Error
import Blog
import Post
import utils

__all__ = [
    'Comment',
    'add_comment',
    'delete_comment',
    'checkAll',
    ]

class Comment(db.Model):
    blog = db.ReferenceProperty(Blog.Blog)
    post = db.ReferenceProperty(Post.Post, required=True)
    date = db.DateTimeProperty(auto_now_add=True)
    author = db.UserProperty(required=True)
    title = db.StringProperty(required=True)
    content = db.TextProperty(required=True)

def add_comment(post, author, title, content):
    """Add a comment to post

    Args:
        post: A Post object to add comment to.
        author: A User object.
        title: Comment title(utf-8 str).
        content: Comment content(utf-8 str).

    Returns:
        the comment object added.
    """
    comment = Comment(blog = post.blog,
                      post = post,
                      author = author,
                      title = utils.toDBString(title),
                      content = utils.toDBText(content)
                      )
    comment.put()
    post.blog.updateComment(1)
    post.comments.append(comment.key())
    post.put()

    return comment

def delete_comment(cid):
    """Add a comment to post

    Args:
        cid: the id of the comment

    Returns:
        None
    """
    comment = Comment.get_by_id(cid)
    if not comment:
        raise Error.PageNotFoundError()

    post = comment.post
    post.comments.remove(comment.key())
    post.put()

    comment.delete()
    post.blog.updateComment(-1)

    return comment

def checkTitle(title):
    if len(title) == 0:
        return False,'title is empty'
    if len(title) > 100:
        return False,'title is too long(must below 100)'
    return True,''

def checkContent(title):
    if len(title) == 0:
        return False,'Content is empty'
    return True,''

def checkAll(title,content):
    cl = [
        checkTitle(title),
        checkContent(content),
          ]
    return all([cr[0] for cr in cl]),[cr[1] for cr in cl]
